import 'dart:io';

import 'package:custom_widgets/custom_widgets.dart';
import 'package:custom_widgets/item/item_normal_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mi_mang_flutter/api/upload_api.dart';
import 'package:mi_mang_flutter/page/setting/personal_info/personal_info_router.dart';
import 'package:mi_mang_flutter/provider/app_theme.dart';
import 'package:mi_mang_flutter/provider/user_provider.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:mi_mang_flutter/widget/dialog/pick_images_dialog.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';

class PersonalInfoPage extends StatefulWidget {
  PersonalInfoPage({Key? key}) : super(key: key);

  @override
  _PersonalInfoPageState createState() => _PersonalInfoPageState();
}

class _PersonalInfoPageState extends State<PersonalInfoPage> {
  final ImagePicker _picker = ImagePicker();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(i18n(context).personalInfo),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: _buildBody(),
        ),
      ),
    );
  }

  Widget _buildBody() {
    return Consumer<UserProvider>(builder: (context, provider, _) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _buildTop(provider),
          ...ItemNormalWidget.divideTiles(childs: <Widget>[
            ItemNormalWidget.item(
              title: i18n(context).nickname,
              subtitle: provider.user?.nickName ?? i18n(context).nickname,
              onTap: () {
                NavigatorUtils.push(context, PersonalInfoRouter.nickname);
              },
            ),
            ItemNormalWidget.item(
              title: i18n(context).sex,
              subtitle: _showSex(provider.user?.sex ?? 0),
              onTap: () {
                SexPickerDialog.show(context).then((val) {
                  if (val != null) {
                    provider.updateUserInfo(sex: val);
                  }
                });
              },
            ),
            ItemNormalWidget.item(
              title: i18n(context).birthDay,
              subtitle: _showBirthday(provider.user?.birthday),
              onTap: () {
                DatePickerSheet.show(
                  context,
                  selectDate: provider.user?.birthday,
                  mode: CupertinoDatePickerMode.date,
                ).then((val) {
                  if (val != null) {
                    provider.updateUserInfo(birthday: val);
                  }
                });
              },
            ),
            ItemNormalWidget.item(
              title: i18n(context).personalityIntroduction,
              subtitle: provider.user?.signature ?? "随便写点什么吧......",
              onTap: () {
                NavigatorUtils.push(context, PersonalInfoRouter.signature);
              },
            ),
          ]),
        ],
      );
    });
  }

  /// 顶部布局
  Widget _buildTop(UserProvider provider) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 50.0),
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                border: Border.all(
                  color: ThemeUtil.isDark(context)
                      ? Color(0xFF5E5E5E)
                      : Color(0xFFEDECEB),
                  width: 5.0,
                ),
                shape: BoxShape.circle,
              ),
              child: ClipOval(
                child: loadNetworkImage(
                  provider.user?.avatar ?? '',
                  placeholder: "public/default_user",
                  width: 80.0,
                  height: 80.0,
                ),
              ),
            ),
            Gaps.vGap12,
            Text(
              i18n(context).updateHeadImage,
            ),
          ],
        ),
      ),
      onTap: () {
        PickImageDialog.show(context)
            .then((index) => _pickImage(provider, index));
      },
    );
  }

  /// 根据sex值判断显示文本
  String _showSex(int sex) {
    String sexStr = "";
    switch (sex) {
      case 1:
        sexStr = i18n(context).man;
        break;
      case 0:
        sexStr = i18n(context).woMan;
        break;
      default:
        sexStr = i18n(context).confidentiality;
    }
    return sexStr;
  }

  /// 出生日期格式化
  String _showBirthday(DateTime? birthday) {
    String birthdayStr = "";
    if (birthday != null) {
      birthdayStr = DateFormat('yyyy-MM-dd').format(birthday);
    }
    return birthdayStr;
  }

  /// 上传图片
  /// [index] 1: 拍照上传, 2: 相册选择
  void _pickImage(UserProvider provider, int? index) {
    if (index == null) return;
    ImageSource source = index == 1 ? ImageSource.camera : ImageSource.gallery;
    _picker
        .pickImage(
            source: source,
            maxWidth: 2000.0,
            maxHeight: 2000.0,
            imageQuality: 80)
        .then((pickedFile) {
      if (pickedFile != null) {
        var file = File(pickedFile.path);
        upload(file).then((val) {
          provider.updateUserInfo(avatar: val.data!.mediaPath);
        });
      }
    }).catchError((error) {
      print(error.toString());
      Toast.showError("选择图片异常");
    });
  }
}
